// orders.js
const api = require('../../utils/api.js')
const permissionUtils = require('../../utils/permissions.js')
const pagePermission = require('../../utils/pagepermission.js')

Page({
  data: {
    orderList: [],
    statusList: ['全部', '待分配', '分配中', '已完成'],
    statusIndex: 0,
    page: 1,
    limit: 10,
    hasMore: true,
    loading: false
  },

  onLoad() {
    // 页面权限检查
    if (!pagePermission.requirePagePermission('pages/orders/orders')) {
      return
    }
    
    this.loadOrders()
  },

  onShow() {
    this.refreshOrders()
  },

  // 加载订单列表
  loadOrders() {
    if (this.data.loading) return
    
    this.setData({ loading: true })
    
    const params = {
      page: this.data.page,
      limit: this.data.limit
    }
    
    if (this.data.statusIndex > 0) {
      params.status = this.data.statusIndex - 1
    }
    
    api.getOrders(params).then(res => {
      const newList = this.data.page === 1 ? res.data.list : [...this.data.orderList, ...res.data.list]
      
      // 格式化时间和处理数据
      newList.forEach(item => {
        item.createtime_text = this.formatTime(item.createtime)
        item.delivery_date = this.formatDate(item.delivery_date)
        // 处理产品型号名称
        if (item.order_models && item.order_models.length > 0) {
          item.model_names = item.order_models.map(om => 
            om.model && om.model.product ? 
            `${om.model.product.name} (编号:${om.model.product.id})-${om.model.name}` : 
            '未知型号'
          ).join(', ')
        } else {
          item.model_names = '无型号信息'
        }
      })
      
      this.setData({
        orderList: newList,
        hasMore: res.data.list.length === this.data.limit,
        loading: false
      })
    }).catch(err => {
      this.setData({ loading: false })
      console.error('加载订单列表失败:', err)
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      })
    })
  },

  // 刷新订单列表
  refreshOrders() {
    this.setData({
      page: 1,
      hasMore: true
    })
    this.loadOrders()
  },

  // 加载更多
  loadMore() {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({
        page: this.data.page + 1
      })
      this.loadOrders()
    }
  },

  // 状态筛选
  onStatusChange(e) {
    this.setData({
      statusIndex: e.detail.value,
      page: 1,
      hasMore: true
    })
    this.loadOrders()
  },

  // 跳转到订单详情
  goToOrderDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/order-detail/order-detail?id=${id}`
    })
  },

  // 跳转到创建订单
  goToCreateOrder() {
    wx.navigateTo({
      url: '/pages/create-order/create-order'
    })
  },

  // 编辑订单
  editOrder(e) {
    const id = e.currentTarget.dataset.id
    // 阻止事件冒泡
    if (e.stopPropagation) {
      e.stopPropagation()
    }
    wx.navigateTo({
      url: `/pages/create-order/create-order?id=${id}`
    })
  },

  // 阻止事件冒泡
  stopPropagation(e) {
    // 空方法，用于阻止事件冒泡
  },

  // 删除订单
  deleteOrder(e) {
    const id = e.currentTarget.dataset.id
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个订单吗？删除后无法恢复。',
      success: (res) => {
        if (res.confirm) {
          this.doDeleteOrder(id)
        }
      }
    })
  },

  // 执行删除订单
  doDeleteOrder(orderId) {
    api.deleteOrder(orderId).then(res => {
      wx.showToast({
        title: '删除成功',
        icon: 'success'
      })
      this.refreshOrders()
    }).catch(err => {
      console.error('删除订单失败:', err)
      wx.showToast({
        title: '删除失败',
        icon: 'error'
      })
    })
  },

  // 格式化时间
  formatTime(timestamp) {
    const date = new Date(timestamp * 1000)
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    const hour = date.getHours().toString().padStart(2, '0')
    const minute = date.getMinutes().toString().padStart(2, '0')
    return `${year}-${month}-${day} ${hour}:${minute}`
  },

  // 格式化日期
  formatDate(dateStr) {
    if (!dateStr) return '未设置'
    const date = new Date(dateStr)
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    return `${year}-${month}-${day}`
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.refreshOrders()
    wx.stopPullDownRefresh()
  },

  // 上拉加载更多
  onReachBottom() {
    this.loadMore()
  },

  // 导航方法
  goToIndex() {
    console.log('点击了首页导航')
    wx.navigateTo({
      url: '/pages/index/index',
      success: () => {
        console.log('跳转到首页成功')
      },
      fail: (err) => {
        console.error('跳转到首页失败:', err)
      }
    })
  },

  goToAllocationManage() {
    console.log('点击了分工管理导航')
    wx.navigateTo({
      url: '/pages/allocation-manage/allocation-manage',
      success: () => {
        console.log('跳转到分工管理成功')
      },
      fail: (err) => {
        console.error('跳转到分工管理失败:', err)
      }
    })
  },

  goToReports() {
    console.log('点击了报工管理导航')
    wx.navigateTo({
      url: '/pages/reports/reports',
      success: () => {
        console.log('跳转到报工管理成功')
      },
      fail: (err) => {
        console.error('跳转到报工管理失败:', err)
      }
    })
  },


}) 